<template>
    <div>
        <span @click="handleVisible(true)" v-if="props?.value?.length" class="selected-btn-box">
            <!-- 自定义选择商品按钮 -->
            <slot name="btn" :selectedRow="selectedRow" :goodIds="goodIds">
                <el-button type="primary" text> {{ btnTitle }} </el-button>
            </slot>
        </span>
        <el-dialog
            class="selected_template_dialog"
            :title="title"
            v-model="visible"
            append-to-body
            width="60%"
            @close="closeCallback()">
            <div class="selected_template_dialog_header">
                <el-form ref="formRef" :model="form" label-width="auto" @submit.prevent>
                    <el-row justify="space-between" :gutter="24">
                        <el-col :span="8">
                            <el-form-item prop="goodsName" label="商品名称">
                                <el-input v-model="form.goodsName" clearable></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8">
                            <el-form-item label="来源店铺" prop="shopId">
                                <el-select v-model="form.shopId" filterable placeholder="全部">
                                    <el-option
                                        v-for="item in shopList"
                                        :key="item.shopId"
                                        :label="item.shopName"
                                        :value="item.shopId" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="8" style="text-align: right">
                            <el-button type="primary" @click="searchHandler">查询</el-button>
                            <el-button @click="resetHandler">清空</el-button>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <el-table
                v-loading="loading"
                :data="tableList"
                style="margin-top: 20px"
                height="350"
                class="selected-good-table"
                ref="multipleTableRef">
                <el-table-column v-for="{ prop, ...rest } in tableColumnsCopy" :key="prop" :prop="prop" v-bind="rest">
                    <template #default="{ row }">
                        <div class="custom-goods-name" v-if="prop === 'goodsName'">
                            <el-image
                                style="width: 40px; height: 40px; min-width: 40px"
                                :src="row?.materialSrc?.[0]?.materialSrc"
                                fit="fill"></el-image>
                            <el-tooltip effect="dark" :content="row.goodsName" placement="top">
                                <span class="custom-goods-name-span">{{ row.goodsName }}</span>
                            </el-tooltip>
                        </div>
                        <el-popconfirm
                            v-if="prop === 'operation'"
                            placement="top"
                            width="250px"
                            title="确定要删除吗？"
                            @confirm="handleRemove(row)"
                            confirm-button-text="确定"
                            cancel-button-text="取消">
                            <template #reference>
                                <el-button v-if="prop === 'operation'" size="small"> 删除</el-button>
                            </template>
                        </el-popconfirm>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <div class="custom-page">
                <Pagination
                    :total="totalCount"
                    :page-size="form.pageSize"
                    :current-page="form.pageNum"
                    @sizeChange="changeSizeHandler"
                    @pageChange="changePageHandler" />
            </div>
        </el-dialog>
    </div>
</template>

<script setup name="SelectedGoods">
import { ref, reactive, onMounted, computed, watch, nextTick } from 'vue';
import { cloneDeep } from '@/commons/utils';
import { ElMessage } from 'element-plus';
import request from '@/request';
import { getGoodsListHook } from '@/hooks/goods';
import Pagination from '@/components/Pagination.vue';
import { getShopListHook } from '@/hooks';

/* ---------------------------------- 父级通信 start ---------------------------------- */
const emit = defineEmits(['handle-confirm']);
const props = defineProps({
    // 商品id集合
    value: {
        type: [Array],
        default: () => null
    },
    disabled: {
        type: Boolean,
        default: false
    }
});
/* ---------------------------------- 父级通信 end ---------------------------------- */

/* ---------------------------------- 查询表格 start ---------------------------------- */
const form = reactive({
    pageNum: 1,
    pageSize: 10,
    goodsName: '',
    shopId: 0
});
const formClone = cloneDeep(form); // 查询表单备份
const formRef = ref();
let shopList = reactive([]); // 店铺下拉列表
let loading = ref(false);

const totalCount = ref(0);
let tableList = reactive([]);
const tableColumns = reactive([
    { label: '商品信息', prop: 'goodsName', minWidth: '200' },
    { label: '销售价', prop: 'price' },
    { label: '库存', prop: 'goodsStock' },
    { label: '来源店铺', prop: 'shopInfoText', width: '200' }
    // { label: '已参与活动', prop: 'activityNameText', minWidth: '200' }
    // { label: '操作', prop: 'operation', width: '100' }
]);
const tableColumnsCopy = computed(() => {
    const cols = cloneDeep(tableColumns);
    if (!props.disabled) {
        cols.push({ label: '操作', prop: 'operation', width: '100' });
    }
    return cols;
});
/* ---------------------------------- 查询表格 end ---------------------------------- */

let selectedRow = reactive({}); // 已选中的商品
const multipleTableRef = ref();
let goodIds = reactive([]); // 多选的商品ids
let goodIdsClone = reactive([]); // 多选的商品ids
watch(
    () => props.value,
    val => {
        if (props.isMulti) {
            goodIds.length = 0;
            goodIdsClone.length = 0;
            Object.assign(goodIds, val || []);
            Object.assign(goodIdsClone, val || []);
            return;
        }
        Object.assign(selectedRow, val || {});
    },
    {
        immediate: true,
        deep: true
    }
);

const toggleRowSelection = rows => {
    rows.forEach(item => {
        multipleTableRef?.value?.toggleRowSelection(item);
    });
};

/* ---------------------------------- 控制弹窗 start ---------------------------------- */
let visible = ref(false);
// 展示隐藏
const handleVisible = (isVisible = false) => {
    visible.value = isVisible;
    if (visible.value) {
        searchHandler();
        getShopList();
    }
};
const closeCallback = visible => {
    // 关闭后重置表格
    form.goodsName = '';
    // searchHandler();
};
const title = computed(() => {
    return `${props.disabled ? '查看' : '已选'}商品`;
});
const btnTitle = computed(() => {
    return `${title.value}（${props?.value?.length}）`;
});
/* ---------------------------------- 控制弹窗 end ---------------------------------- */

const handleRemove = row => {
    emit('handle-remove', row.id);
    nextTick(() => {
        if (!props?.value?.length) {
            handleVisible(false);
            return;
        }
        queryCouponListHandler();
    });
};

const handleSelectionChange = val => {
    // goodIds
    if (!visible.value) {
        return;
    }
    nextTick(() => {
        const selectList = val.map(item => item.id);
        const notSelectedList = tableList.reduce((prev, { id }) => {
            if (!selectList.includes(id)) {
                prev.push(id);
            }
            return prev;
        }, []);
        const ids = goodIds.filter(item => !notSelectedList.includes(item));
        goodIds.length = 0;
        Object.assign(goodIds, [...new Set([...ids, ...selectList])]);
    });
};

/**
 * 重置
 */
const resetHandler = () => {
    formRef.value.resetFields();
    Object.assign(form, formClone);
    searchHandler();
};

/**
 * 搜索
 */
const searchHandler = () => {
    form.pageNum = 1;
    queryCouponListHandler();
};
/**
 * 分页
 * @param {*} pageNum
 */
const changePageHandler = pageNum => {
    form.pageNum = pageNum;
    queryCouponListHandler();
};

/**
 * 每页记录数修改
 * @param {*} pageSize
 */
const changeSizeHandler = pageSize => {
    form.pageNum = 1;
    form.pageSize = pageSize;
    queryCouponListHandler();
};
/**
 * 分页查询
 */
const queryCouponListHandler = async () => {
    loading.value = true;
    // todo:商品列表服务
    const { data } = await getGoodsListHook({ ...form, goodsIds: props.value });
    tableList.length = 0;
    Object.assign(
        tableList,
        (data.list || []).map(item => {
            if (item.goodsMinPrice === item.goodsMaxPrice) {
                item.price = `￥${item.goodsMinPrice / 100}`;
            } else {
                item.price = `￥${item.goodsMinPrice / 100}~￥${item.goodsMaxPrice / 100}`;
            }
            item.shopInfoText = item?.shopInfo?.[0]?.shopName;
            item.activityNameText = item?.partakeActivity?.length ? item?.partakeActivity?.join() : '-';
            return item;
        })
    );
    totalCount.value = data.totalCount;
    loading.value = false;
};

// 获取店铺
const getShopList = async () => {
    const { data } = await getShopListHook();
    shopList.length = 0;
    const list = data?.list || [];
    list.unshift({ shopName: '全部', shopId: 0 });
    Object.assign(shopList, list);
};

onMounted(() => {
    // getshopList();
    // searchHandler();
});
</script>

<style lang="scss">
.selected_template_dialog {
    max-width: 1000px;
    min-width: 900px;
    /* min-height: 570px; */
    .selected-good-table {
        border-bottom: 1px solid #eaeaea !important;
    }
}
</style>
<style lang="scss" scoped>
.selected-btn-box {
    :deep {
        .el-button.is-text:not(.is-disabled):hover,
        .el-button.is-text:not(.is-disabled):focus {
            background-color: unset;
        }
    }
}
.selected_template_dialog {
    &_header {
        width: 100%;
        .el-form > div {
            flex-wrap: nowrap;
        }
    }
    .center-operation {
        padding: 20px 0;
        display: flex;
        border-bottom: 1px solid #eaeaea;
        justify-content: space-between;
    }
    .custom-goods-name {
        display: inline-flex;
        align-items: center;
        width: 100%;
        &-span {
            margin-left: 4px;
            display: -webkit-box;
            max-width: calc(100% - 45px);
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 2;
            overflow: hidden;
        }
    }
    .custom-page {
        height: auto;
        overflow: hidden;
    }
    .custom-footer {
        flex: 1 1 auto;
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;
    }
    .selected-total {
        font-size: 14px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #33302d;
        span {
            margin: 0 4px;
            color: #ff6b00;
        }
    }
}
</style>
